<template>
  <div class="calendar-view">
    <AppHeader title="日历" />

    <el-pull-refresh @refresh="onRefresh">
      <div class="calendar-header">
        <div class="date-nav">
          <el-button-group>
            <el-button @click="previousDate">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <el-button @click="nextDate">
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </el-button-group>
          <span class="current-date" @click="showYearMonthPicker = true">
            {{ currentDateDisplay }}
          </span>
        </div>
        <div class="view-switcher">
          <el-radio-group v-model="currentView" size="small">
            <el-radio-button label="month">月</el-radio-button>
            <el-radio-button label="week">周</el-radio-button>
            <el-radio-button label="day">日</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div class="calendar-body">
        <!-- 月视图 -->
        <div v-if="currentView === 'month'" class="month-view">
          <div class="weekdays">
            <span v-for="day in weekDays" :key="day">{{ day }}</span>
          </div>
          <div class="days">
            <div
              v-for="(day, index) in daysInMonth"
              :key="index"
              :class="[
                'day',
                { 'other-month': day.otherMonth },
                { 'today': isToday(day.date) },
                { 'selected': isSelected(day.date) }
              ]"
              @click="selectDate(day.date)"
            >
              <span class="day-number">{{ day.dayNumber }}</span>
              <div class="day-marker" v-if="day.hasTask"></div>
            </div>
          </div>
        </div>

        <!-- 周视图 -->
        <div v-if="currentView === 'week'" class="week-view">
          <div class="weekdays">
            <span v-for="day in weekDays" :key="day">{{ day }}</span>
          </div>
          <div class="days">
            <div
              v-for="(day, index) in daysInWeek"
              :key="index"
              :class="[
                'day',
                { 'today': isToday(day.date) },
                { 'selected': isSelected(day.date) }
              ]"
              @click="selectDate(day.date)"
            >
              <span class="day-number">{{ day.dayNumber }}</span>
              <div class="day-marker" v-if="day.hasTask"></div>
            </div>
          </div>
        </div>

        <!-- 日视图 -->
        <div v-if="currentView === 'day'" class="day-view">
          <div class="day-header">
            {{ selectedDateDisplay }}
          </div>
        </div>
      </div>

      <!-- 选中日期的任务列表 -->
      <div class="tasks-section">
        <div class="section-header">
          <h3>{{ selectedDateDisplay }} 任务</h3>
        </div>
        <div class="task-list">
          <div v-if="tasks.length === 0" class="no-tasks">
            暂无任务
          </div>
          <div
            v-for="task in tasks"
            :key="task.id"
            class="task-item"
          >
            <el-checkbox
              :model-value="task.status === 2"
              @change="() => handleTaskComplete(task)"
            >
              {{ task.title }}
            </el-checkbox>
          </div>
        </div>
      </div>

      <!-- 年月选择器 -->
      <el-dialog
        v-model="showYearMonthPicker"
        title="选择年月"
        width="300px"
      >
        <div class="year-month-picker">
          <el-date-picker
            v-model="currentDate"
            type="month"
            format="YYYY年MM月"
            @change="handleYearMonthChange"
          />
        </div>
      </el-dialog>
    </el-pull-refresh>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import axios from 'axios'
import AppHeader from '../components/AppHeader.vue'

dayjs.locale('zh-cn')

export default {
  name: 'CalendarView',
  components: {
    ArrowLeft,
    ArrowRight,
    AppHeader
  },
  setup() {
    const store = useStore()
    const currentView = ref('month')
    const currentDate = ref(dayjs())
    const selectedDate = ref(dayjs())
    const showYearMonthPicker = ref(false)
    const weekDays = ['日', '一', '二', '三', '四', '五', '六']
    const tasks = ref([])

    // 日期显示计算属性
    const currentDateDisplay = computed(() => {
      return currentDate.value.format('YYYY年MM月')
    })

    const selectedDateDisplay = computed(() => {
      return selectedDate.value.format('YYYY年MM月DD日')
    })

    // 获取月视图数据
    const daysInMonth = computed(() => {
      const firstDay = currentDate.value.startOf('month')
      const lastDay = currentDate.value.endOf('month')
      const startDay = firstDay.startOf('week')
      const endDay = lastDay.endOf('week')
      
      const days = []
      let day = startDay
      
      while (day.isBefore(endDay) || day.isSame(endDay, 'day')) {
        days.push({
          date: day,
          dayNumber: day.date(),
          otherMonth: day.month() !== currentDate.value.month(),
          hasTask: false // 这里需要根据实际任务数据判断
        })
        day = day.add(1, 'day')
      }
      
      return days
    })

    // 获取周视图数据
    const daysInWeek = computed(() => {
      const startOfWeek = currentDate.value.startOf('week')
      const days = []
      
      for (let i = 0; i < 7; i++) {
        const day = startOfWeek.add(i, 'day')
        days.push({
          date: day,
          dayNumber: day.date(),
          hasTask: false // 这里需要根据实际任务数据判断
        })
      }
      
      return days
    })

    // 新增：按日期请求任务
    const fetchTasksByDate = async (dateStr) => {
      try {
        const response = await axios.get('/zwart/user/task/by-expect-date', {
          params: { expect_date: dateStr }
        })
        if (response.data.code === 200) {
          tasks.value = response.data.data
        } else if (Array.isArray(response.data)) {
          tasks.value = response.data
        } else {
          tasks.value = []
        }
      } catch (error) {
        console.error('Error fetching tasks by date:', error)
        tasks.value = []
      }
    }

    // 修改 selectDate
    const selectDate = (date) => {
      selectedDate.value = date
      const dateStr = date.format('YYYY-MM-DD')
      fetchTasksByDate(dateStr)
    }

    // 页面加载时默认请求今天
    onMounted(() => {
      const dateStr = selectedDate.value.format('YYYY-MM-DD')
      fetchTasksByDate(dateStr)
    })

    // 日期操作方法
    const previousDate = () => {
      if (currentView.value === 'month') {
        currentDate.value = currentDate.value.subtract(1, 'month')
      } else if (currentView.value === 'week') {
        currentDate.value = currentDate.value.subtract(1, 'week')
      } else {
        currentDate.value = currentDate.value.subtract(1, 'day')
      }
    }

    const nextDate = () => {
      if (currentView.value === 'month') {
        currentDate.value = currentDate.value.add(1, 'month')
      } else if (currentView.value === 'week') {
        currentDate.value = currentDate.value.add(1, 'week')
      } else {
        currentDate.value = currentDate.value.add(1, 'day')
      }
    }

    const handleYearMonthChange = () => {
      showYearMonthPicker.value = false
    }

    const isToday = (date) => {
      return date.isSame(dayjs(), 'day')
    }

    const isSelected = (date) => {
      return date.isSame(selectedDate.value, 'day')
    }

    const handleTaskComplete = async (task) => {
      const newStatus = task.status === 2 ? 1 : 2
      await store.dispatch('updateTask', { ...task, status: newStatus })
      await fetchTasksByDate(selectedDate.value.format('YYYY-MM-DD'))
    }

    const onRefresh = async (done) => {
      await fetchTasksByDate(selectedDate.value.format('YYYY-MM-DD'))
      done()
    }

    return {
      currentView,
      currentDate,
      selectedDate,
      showYearMonthPicker,
      weekDays,
      currentDateDisplay,
      selectedDateDisplay,
      daysInMonth,
      daysInWeek,
      tasks,
      previousDate,
      nextDate,
      selectDate,
      handleYearMonthChange,
      isToday,
      isSelected,
      handleTaskComplete,
      fetchTasksByDate,
      onRefresh
    }
  }
}
</script>

<style lang="scss" scoped>
.calendar-view {
  padding: 15px;
  padding-top: 60px;
  min-height: 100vh;
  padding-bottom: 65px;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  gap: 15px;

  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 5px;

    .date-nav {
      display: flex;
      align-items: center;
      gap: 15px;

      .current-date {
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
      }
    }
  }

  .calendar-body {
    background: #fff;
    border-radius: 12px;
    padding: 15px;
    height: calc(45vh - 100px);
    min-height: 300px;

    .weekdays {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      text-align: center;
      margin-bottom: 8px;
      font-weight: bold;
      color: #606266;
      font-size: 14px;
    }

    .days {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 4px;
      height: calc(100% - 30px);

      .day {
        aspect-ratio: auto;
        padding: 4px;
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;
        border-radius: 6px;
        position: relative;
        font-size: 13px;

        &.other-month {
          color: #c0c4cc;
        }

        &.today {
          background-color: #e6f1fe;
          color: #409eff;
        }

        &.selected {
          background-color: #409eff;
          color: #fff;

          .day-marker {
            background-color: #fff;
          }
        }

        .day-number {
          font-size: 13px;
          margin-bottom: 2px;
        }

        .day-marker {
          width: 4px;
          height: 4px;
          border-radius: 50%;
          background-color: #409eff;
        }
      }
    }
  }

  .tasks-section {
    background: #fff;
    border-radius: 12px;
    padding: 15px;
    flex: 1;
    height: calc(45vh - 50px);
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .section-header {
      margin-bottom: 15px;
      padding: 0 5px;

      h3 {
        margin: 0;
        color: #303133;
        font-size: 16px;
      }
    }

    .task-list {
      flex: 1;
      overflow-y: auto;
      padding: 0 5px;

      .no-tasks {
        text-align: center;
        color: #909399;
        padding: 20px 0;
      }

      .task-item {
        padding: 10px;
        border-radius: 8px;
        background-color: #f8f9fa;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }

        :deep(.el-checkbox) {
          width: 100%;
          
          .el-checkbox__label {
            white-space: normal;
            word-break: break-all;
            font-size: 14px;
            line-height: 1.4;
          }
        }
      }
    }
  }
}

:deep(.el-dialog) {
  border-radius: 12px;
  
  .el-dialog__header {
    margin: 0;
    padding: 15px;
    border-bottom: 1px solid #dcdfe6;
  }
  
  .el-dialog__body {
    padding: 15px;
  }
  
  .el-dialog__footer {
    padding: 10px 15px;
    border-top: 1px solid #dcdfe6;
  }
}
</style> 